package TCPClient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Arrays;

import messangerTypes.*;

import messangerTypes.MessangerSettings;

public class TCPClientMulticastReader extends Thread
{
	private MulticastSocket sock;
	private TCPClient parent;
	public boolean quit = false;
	
	public TCPClientMulticastReader (TCPClient client) throws IOException
	{
		parent = client;
		InetAddress host = InetAddress.getByName(MessangerSettings.getMulticastaddress());
		sock = new MulticastSocket(MessangerSettings.getMcastport());
		sock.setReuseAddress(MessangerSettings.isSetreuseaddress());
		sock.setLoopbackMode(false);
		sock.joinGroup(host);	
	}
		
	public void run ()
	{
		//TODO: dangerous. neither side has taken into account fragmentation 
		//will take a look at handling if i run out of things to do.
		byte [] buffer = new byte[65535];
		DatagramPacket packet = null;
		MessageBase mb = null;
		
		try
		{
			while (!quit)
			{
				System.out.println("waiting for multicast!");
				//create packet
				packet = new DatagramPacket(buffer, buffer.length);
				//read into packet
				sock.receive(packet);
				//cast the MessageBase out of it
				mb = MessageBase.createObjectFromBytes(packet.getData());
				//pass it on to the client for processing
				parent.processMessage(mb);
				//clear the buffer to prep for reuse
				Arrays.fill(buffer, (byte)0);
				System.out.println("got a mutlicast message!");
			}
			
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				sock.leaveGroup(InetAddress.getByName(MessangerSettings.getMulticastaddress()));
			} catch (UnknownHostException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sock.close();
		}
		
		
	}
}
